<template>
	<view>
		<view class="pb-16">
			<u-row gutter="10">
				<u-col :span="span" v-for="(item,index) in images" :key="index">
					<view class="image-upload-box mt-10">
						<image :src="item" mode="aspectFill"></image>
						<view class="del-box" @click="delImage(index)">
							<u-icon name="close-circle" color="red" size="24"></u-icon>
						</view>
					</view>
				</u-col>
				<u-col :span="span" v-if="images.length < count">
					<view class="image-upload-box mt-10" @click="uploadImage">
						<view class="upload-box">
							<u-icon name="plus" color="#B2ABA5" size="32"></u-icon>
						</view>
					</view>
				</u-col>
				<u-col span="6">
					<view class="fw-400 fs-12 lh-2 color-5F6865 ps-8" v-if="!images.length">文件格式为jpg/png</view>
				</u-col>
			</u-row>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			count: {
				type: Number, //最大上传张数
				default: 9
			},
			span: {
				type: Number, //图片布局宽度
				default: 4
			}

		},
		data() {
			return {
				images: []
			}
		},
		methods: {
			delImage(index) {
				this.images.splice(index, 1);
				this.$emit('uploadChange', this.images);
			},
			//选择图片上传
			uploadImage() {
				uni.chooseImage({
					count: this.images.length ? this.count : this.count - this.images.length,
					success: (chooseImageRes) => {
						uni.showLoading({
							title: '加载中...',
							mask: true
						});

						if (chooseImageRes.tempFilePaths.length) {
							chooseImageRes.tempFilePaths.map(image => {
								uni.uploadFile({
									url: this.$allConfig.uploadUrl,
									filePath: image,
									name: 'file',
									header: {
										'Authorization': uni.getStorageSync("userInfo").token,
										'type': 'uni-app'
									},
									success: (r) => {
										console.log('上传成功', JSON.parse(r.data))
										this.images.push(JSON.parse(r.data).data.url);
										this.$emit('uploadChange', this.images);
										uni.hideLoading();
									},
									fail: err => {
										this.$f.msg('选择图片失败，请重试');
										uni.hideLoading();
									}
								});
							})
						}
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	.image-upload-box {
		width: 100%;
		height: 0;
		padding-bottom: 100%;
		position: relative;

		image {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			border-radius: 16rpx;
		}

		.del-box {
			position: absolute;
			top: 4rpx;
			right: 4rpx;
		}

		.upload-box {
			display: flex;
			align-items: center;
			justify-content: center;
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			border-radius: 16rpx;
			border: 1px dashed #B2ABA5;
		}

	}
</style>